package com.github.ylt.protocol.ssdp.server;

import com.github.ylt.conf.Configure;
import com.github.ylt.protocol.ssdp.Protocol;
import com.github.ylt.utils.IpUtils;
import com.github.ylt.utils.TimeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.net.*;
import java.util.Timer;
import java.util.TimerTask;

public class ServerImpl extends Server {
    private final Log log = LogFactory.getLog(ServerImpl.class);
    private final String MULTICAST_ADDRESS = Configure.DEFAULT_MULTICAST_ADDRESS;
    private final int MULTICAST_PORT = Configure.DEFAULT_MULTICAST_PORT;
    private final NetworkInterface networkInterface = IpUtils.getInstance().getNetworkInterface();
    private boolean complete = false;
    private boolean closed = false;
    private boolean activeNotification = false;
    private boolean WHETHER_TO_SCAN_DEVICES = Configure.DEFAULT_SCANNING_DEVICE;
    private Timer discoveryTimer;
    private Timer notifyTimer;
    private DiscoveryTask discoveryTask;
    private DatagramSocket socket;

    public ServerImpl() {
        try {
            this.socket = new DatagramSocket(this.MULTICAST_PORT);
            this.socket.setOption(StandardSocketOptions.SO_REUSEADDR,true);
            this.socket.setOption(StandardSocketOptions.IP_MULTICAST_LOOP, true);
            this.socket.setOption(StandardSocketOptions.SO_BROADCAST,true);
            this.socket.setOption(StandardSocketOptions.IP_MULTICAST_TTL,60);
            this.socket.setOption(StandardSocketOptions.TCP_NODELAY,true);
            this.socket.setOption(StandardSocketOptions.IP_MULTICAST_IF, networkInterface);
            this.socket.setOption(StandardSocketOptions.SO_SNDBUF,1024);
            this.socket.setOption(StandardSocketOptions.SO_RCVBUF,1024);
            this.socket.joinGroup(new InetSocketAddress(MULTICAST_ADDRESS, MULTICAST_PORT),networkInterface);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Server createServer() {
        return null;
    }

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }

    @Override
    public int getPort() {
        return 0;
    }

    @Override
    public String getHost() {
        return "";
    }

    public void enableDiscoveryDevice(){
        this.WHETHER_TO_SCAN_DEVICES = true;
        if(discoveryTask == null){
            discoveryTask = new DiscoveryTask();
        }
        if(discoveryTimer == null){
            discoveryTimer = new Timer("discovery-timer",true);
        }
        this.discoveryTimer.schedule(discoveryTask, 1000, 1000);
    }

    private class DiscoveryTask extends TimerTask {

        private int length = 0;

        @Override
        public void run() {
           if(WHETHER_TO_SCAN_DEVICES){
           }
        }
    }
}
